﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


class BufferedConsole : IDisposable
{
    private const int DefaultBufferSize = 50;
    private int cuttentBufferSize;
    private StringBuilder buffer;
    private int flushNumber = 0;
    private string name;

    public StringBuilder Buffer
    {
      get { return buffer; }
    }

    public BufferedConsole(string name)
    {
        this.buffer = new StringBuilder(BufferedConsole.DefaultBufferSize);
        this.cuttentBufferSize = DefaultBufferSize;
        this.name = name;
    }

    public BufferedConsole(int bufferSize, string name) 
    {
        this.buffer = new StringBuilder(bufferSize);
        this.cuttentBufferSize = bufferSize;
        this.name = name;
    }

    public void Write(string text)
    {
        int freeBytes = this.cuttentBufferSize - this.buffer.Length;
        if (freeBytes > text.Length)
        {
            this.buffer.Append(text);
        }
        else
        {
            int textIndex = 0;
            int remainingText = text.Length;
            while (freeBytes <= remainingText)
            {
                this.buffer.Append(text.Substring(textIndex, freeBytes));
                Flush();
                textIndex += freeBytes;
                remainingText -= freeBytes;
                freeBytes = this.cuttentBufferSize;
            }
            this.buffer.Append(text.Substring(textIndex));
        }
    }

    public void Flush()
    {
        Console.WriteLine("{0}({1}): {2}",this.name, this.flushNumber, this.buffer);
        this.buffer.Clear();
        this.flushNumber++;
    }

    ~BufferedConsole()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        Flush();
        if (disposing)
        {
            // Free any managed resources here
            this.buffer = null;
        }
        else
        {
            // Deallocated the unmanaged resources here
        }
    }
}
